/**
 * 防抖
 * @param {Function} fn 执行函数
 * @param {Number} delay 延时 (ms)
 */
export const debounce = (fn, delay = 1000) => {
  let timer = null;
  return function () {
    if (timer) {
      clearTimeout(timer);
    }
    timer = setTimeout(fn, delay);
  };
};

/**
 * 节流
 * @param {Function} fn 执行函数
 * @param {Number} delay 延时 (ms)
 * @returns
 */
export const throttle = (fn, delay = 500) => {
  let _throttle = false;
  return function () {
    if (_throttle) {
      return;
    }
    _throttle = true;
    fn();
    setTimeout(() => {
      _throttle = false;
    }, delay);
  };
};
/**
 * 显示uniToast
 * @param {String} text  提示文本
 * @param {Object} param  参数
 */
export const msg = (text, param = {}) => {
  if (!text) {
    return;
  }
  uni.showToast({
    title: text,
    icon: param.icon || 'none',
    mask: param.mask || false,
    duration: param.duration || 1500,
  });
};

/**
 * 时间格式化
 * @param {String} fmt  格式 YYYY-mm-dd HH:MM  (2021-03-26 12:33)
 * @param {Time} date  时间
 * @returns String
 */
export const formatTime = (fmt, date) => {
  let ret;
  const opt = {
    'Y+': date.getFullYear().toString(), // 年
    'm+': (date.getMonth() + 1).toString(), // 月
    'd+': date.getDate().toString(), // 日
    'H+': date.getHours().toString(), // 时
    'M+': date.getMinutes().toString(), // 分
    'S+': date.getSeconds().toString(), // 秒
  };
  for (let k in opt) {
    ret = new RegExp('(' + k + ')').exec(fmt);
    if (ret) {
      fmt = fmt.replace(
        ret[1],
        ret[1].length == 1 ? opt[k] : opt[k].padStart(ret[1].length, '0')
      );
    }
  }
  return fmt;
};
/**
 * 深拷贝
 * @param {Any} target  克隆的目标
 * @returns Any
 */
export const deepClone = (target) => {
  if (typeof target != 'object') {
    // 不是对象直接返回
    return target;
  }
  if (Array.isArray(target)) {
    //数组拷贝
    return [...target];
  } else if (target === null) {
    return null;
  } else if (target.constructor === RegExp) {
    return target;
  } else {
    return {
      ...target,
    };
  }
};

/**
 * obj转paramQuery
 * @param {Object} target  转换的目标
 * @returns String
 */
export const paramQuery = (target) => {
  if (typeof target != 'object') {
    console.error('传入参数格式错误');
    return;
  }

  let paramStr = '';

  for (let key in target) {
    if (Array.isArray(target[key])) {
      paramStr += `&${key}=${target[key].join(',')}`;
    } else {
      paramStr += `&${key}=${encodeURIComponent(target[key])}`;
    }
  }
  return paramStr.replace(/^[&]{1}/, '?');
};
/**
 * 正则表达式
 * @param {String} str  字符串
 * @param {String} type  类型
 * @returns Bool
 */
export const checkStr = (str, type) => {
  switch (type) {
    case 'mobile': //手机号码
      return /^1[3|4|5|6|7|8|9][0-9]{9}$/.test(str);
    case 'tel': //座机
      return /^(0\d{2,3}-\d{7,8})(-\d{1,4})?$/.test(str);
    case 'card': //身份证
      return /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(str);
    case 'mobileCode': //6位数字验证码
      return /^[0-9]{6}$/.test(str);
    case 'pwd': //密码以字母开头，长度在6~18之间，只能包含字母、数字和下划线
      return /^([a-zA-Z0-9_]){6,18}$/.test(str);
    case 'payPwd': //支付密码 6位纯数字
      return /^[0-9]{6}$/.test(str);
    case 'postal': //邮政编码
      return /[1-9]\d{5}(?!\d)/.test(str);
    case 'QQ': //QQ号
      return /^[1-9][0-9]{4,9}$/.test(str);
    case 'email': //邮箱
      return /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/.test(str);
    case 'money': //金额(小数点2位)
      return /^\d*(?:\.\d{0,2})?$/.test(str);
    case 'URL': //网址
      return /(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?/.test(
        str
      );
    case 'IP': //IP
      return /((?:(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d))/.test(
        str
      );
    case 'date': //日期时间
      return (
        /^(\d{4})\-(\d{2})\-(\d{2}) (\d{2})(?:\:\d{2}|:(\d{2}):(\d{2}))$/.test(
          str
        ) || /^(\d{4})\-(\d{2})\-(\d{2})$/.test(str)
      );
    case 'number': //数字
      return /^[0-9]$/.test(str);
    case 'english': //英文
      return /^[a-zA-Z]+$/.test(str);
    case 'chinese': //中文
      return /^[\\u4E00-\\u9FA5]+$/.test(str);
    case 'lower': //小写
      return /^[a-z]+$/.test(str);
    case 'upper': //大写
      return /^[A-Z]+$/.test(str);
    case 'HTML': //HTML标记
      return /<("[^"]*"|'[^']*'|[^'">])*>/.test(str);
    default:
      return true;
  }
};

/**
 * 二维数组去重
 * @param {ArrAy} arr  数组
 * @returns Array
 */
export const getUnique = (arr) => {
  let obj = {};
  return arr.filter((item, index) => {
    let newItem = item + JSON.stringify(item);
    return obj.hasOwnProperty(newItem) ? false : (obj[newItem] = true);
  });
};
/**
 * 获取页面栈
 * @param {Number} index  1表示获取上一页
 * @returns Object
 */
export const prePage = (index) => {
  const pages = getCurrentPages();
  if (pages.length > 1) {
    let beforePage = pages[pages.length - (index + 1)];
    return beforePage.$vm;
  }
  return null;
};

/**
 *  是否是图片
 * @param {*} str
 */
export const isImage = (str) => {
  const s = str.substring(str.length - 3, str.length);

  if (s === 'png' || s === 'jpg' || s === 'gif') {
    return true;
  }

  return false;
};
/**
 *  图片查看
 * @param {*} imgs
 */
import { downloadBaseUrl } from '@/config.js';
export const previewImage = (imgs) => {
  // let imgList = imgs.map((m) => (m = downloadBaseUrl + m));
  let imgList = imgs;
  uni.previewImage({
    urls: imgList,
    longPressActions: {
      itemList: ['暂不支持任何操作'],
      success: function (data) {
        uni.showToast({
          title: '暂不支持图片保存',
          duration: 2000,
          icon: 'none',
        });
      },
      fail: function (err) {},
    },
  });
};

export const getStatusByName = (name) => {
  return new Promise((resolve, reject) => {
    uni.$zx.order_api.getOrderStatus().then((data) => {
      let res = data;
      res.forEach((e) => {
        if (e.name === name) {
          resolve(e.value);
        }
      });
    });
    reject(null);
  });
};
/**
 * 打开文档
 */
export const openDocument = (url) => {
  uni.downloadFile({
    url: uni.$zx.deliverDownloadBaseUrl + url,
    success: function (res) {
      var filePath = res.tempFilePath;
      uni.openDocument({
        filePath: filePath,
        success: function (res) {},
        fail: function (err) {
          console.error(err);
        },
      });
    },
    fail: function (err) {
      console.error(err);
    },
  });
};

const formatNumber = (n) => {
  n = n.toString();
  return n[1] ? n : `0${n}`;
};

/**
 *  rsa加密
 * @param {*} imgs
 */
import JSEncrypt from './jsencrypt.js';
export const RSAencrypt = (str) => {
  let jse = new JSEncrypt();

  jse.setPublicKey(
    'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDnyo1CsYjdcL1Qrpt9Nm2NAvn5WgJOUFCevQyHf6z8zFMUpqrul3ZOsDaIxw9nfv52rToVsEK2JgRGlLSmCIuPpZwMjkjERNXNnZPqFM4dwLMQIb+P9wf/xX3kb5LtPj7gYHzXeFQI94qvOS+lPwgQbA+zmDx7tswGOLASKTRr3QIDAQABMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDnyo1CsYjdcL1Qrpt9Nm2NAvn5WgJOUFCevQyHf6z8zFMUpqrul3ZOsDaIxw9nfv52rToVsEK2JgRGlLSmCIuPpZwMjkjERNXNnZPqFM4dwLMQIb+P9wf/xX3kb5LtPj7gYHzXeFQI94qvOS+lPwgQbA+zmDx7tswGOLASKTRr3QIDAQAB'
  );
  console.log('str=' + str);
  return jse.encrypt(str);
};

/**
 *  md5加密
 * @param {*} imgs
 */
import Md5 from './md5.js';
export const md5Str = (str) => {
  return Md5.hex_md5(str);
};
